package org.bobo.modules.oss.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.bobo.common.util.DataUtils;
import org.bobo.modules.oss.entity.OSSFile;
import org.bobo.bean.UserDO;
import org.bobo.common.system.vo.LoginUser;
import org.bobo.common.util.CommonUtils;
import org.bobo.common.util.oss.OssBootUtil;
import org.bobo.modules.oss.mapper.OSSFileMapper;
import org.bobo.modules.oss.service.IOSSFileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

@Service("ossFileService")
public class OSSFileServiceImpl extends ServiceImpl<OSSFileMapper, OSSFile> implements IOSSFileService {

	@Override
	public String uploadUser(MultipartFile multipartFile) throws IOException {
		String fileName = multipartFile.getOriginalFilename();
		fileName = CommonUtils.getFileName(fileName);
		OSSFile ossFile = new OSSFile();
		ossFile.setFileName(fileName);
		String fileAddress="upload/"+ DataUtils.dateToString("yyyyMMdd",new Date());
		String url = OssBootUtil.upload(multipartFile,fileAddress);
		//update-begin--Author:scott  Date:20201227 for：JT-361【文件预览】阿里云原生域名可以文件预览，自己映射域名kkfileview提示文件下载失败-------------------
		// 返回阿里云原生域名前缀URL
		ossFile.setUrl(OssBootUtil.getOriginalUrlBoBo(url));
//		ossFile.setUrl(url);
		//update-end--Author:scott  Date:20201227 for：JT-361【文件预览】阿里云原生域名可以文件预览，自己映射域名kkfileview提示文件下载失败-------------------
		UserDO userDO= (UserDO) SecurityUtils.getSubject().getPrincipal();
		ossFile.setType(1);//用户上传
		ossFile.setCreateBy(String.valueOf(userDO.getId()));
		this.save(ossFile);

		return ossFile.getUrl();
	}

	@Override
	public String uploadAdmin(MultipartFile multipartFile) throws IOException {
		String fileName = multipartFile.getOriginalFilename();
		fileName = CommonUtils.getFileName(fileName);
		OSSFile ossFile = new OSSFile();
		ossFile.setFileName(fileName);
		String fileAddress="upload/"+DataUtils.dateToString("yyyyMMdd",new Date());
		String url = OssBootUtil.upload(multipartFile,fileAddress);
		//update-begin--Author:scott  Date:20201227 for：JT-361【文件预览】阿里云原生域名可以文件预览，自己映射域名kkfileview提示文件下载失败-------------------
		// 返回阿里云原生域名前缀URL
		ossFile.setUrl(OssBootUtil.getOriginalUrlBoBo(url));
//		ossFile.setUrl(url);
		//update-end--Author:scott  Date:20201227 for：JT-361【文件预览】阿里云原生域名可以文件预览，自己映射域名kkfileview提示文件下载失败-------------------
		LoginUser adminUser= (LoginUser) SecurityUtils.getSubject().getPrincipal();
		ossFile.setType(2);//后台上传
		ossFile.setCreateBy(String.valueOf(adminUser.getId()));
		this.save(ossFile);

		return ossFile.getUrl();
	}

	@Override
	public boolean delete(OSSFile ossFile) {
		try {
			this.removeById(ossFile.getId());
			OssBootUtil.deleteUrl(ossFile.getUrl());
		}
		catch (Exception ex) {
			return false;
		}
		return true;
	}

}
